<template>
  <!-- 我的售卖品顶部界面 -->
  <div class="personHeadMoudle">
    <PersonHead />
  </div>

  <!-- 我的售卖品主体界面 -->
  <div class="personDataModule">
    <!-- 我的售卖品界面导航 -->
    <div class="personMenuModule">
      <PersonMenu />
    </div>

    <div class="dataModule">
      <div class="personHandleModule">
        <span>商品查询:</span>
        <el-input
          v-model="offerID"
          style="width: 20%"
          placeholder="请输入商品订单号"
          clearable
        />
        <el-button type="primary" :icon="Search" @click="searchOffer"
          >查询ID</el-button
        >
        <el-button type="success" :icon="Plus" @click="addOfferModule = true"
          >新增商品</el-button
        >
      </div>

      <div class="personTableModule">
        <el-table
          :data="tableData"
          :header-cell-style="{
            color: '#000',
            backgroundColor: '#e7f8fd',
            textAlign: 'center',
          }"
          :row-style="{ height: '90px' }"
          :cell-style="{
            textAlign: 'center',
          }"
        >
          <el-table-column property="offerID" width="160px" label="商品ID" />
          <el-table-column label="商品图片">
            <template #default="data">
              <img
                :src="data.row.offerImage"
                alt="商品展示图片"
                style="height: 60px; width: auto"
              />
            </template>
          </el-table-column>
          <el-table-column property="offerName" label="商品名称" />
          <el-table-column property="offerStyle" label="商品类别" />
          <el-table-column property="offerPrice" label="商品原价" />
          <el-table-column property="offerLocal" label="商品地址" />
          <el-table-column property="offerDiscount" label="商品折扣" />
          <el-table-column property="offerDegree" label="商品程度" />
          <el-table-column property="finalPrice" label="最终价格" />
          <el-table-column width="200px" label="操作">
            <template #default="scope">
              <el-button
                type="success"
                :icon="Edit"
                text
                @click="alterOffer(scope.row)"
                >修改</el-button
              >
              <el-button
                type="danger"
                :icon="Delete"
                text
                @click="deleteOffer(scope.row)"
                >撤销</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页栏部分 -->
      <div class="pagiNation">
        <el-pagination
          :page-size="5"
          :pager-count="5"
          :current-page="pageNum.value"
          layout="prev, pager, next"
          :total="totalNum"
          @current-change="currentChange"
        />
      </div>
    </div>
  </div>

  <!-- 个人界面底栏 -->
  <div class="personButtomModule">
    <PersonButtom />
  </div>

  <!-- 新增商品信息弹窗 -->
  <el-dialog v-model="addOfferModule" title="新增商品信息">
    <div class="addOfferModule">
      <div class="addOfferMessage">
        <div class="addMessageModule">
          <a>商品名称：</a>
          <el-input
            v-model="addOfferName"
            placeholder="请输入商品名称"
            style="width: 200px"
            clearable
          />
        </div>
        <div class="addMessageModule">
          <a>商品类型：</a>
          <el-select
            v-model="addOfferStyle"
            placeholder="请选择商品类型"
            style="width: 200px"
            clearable
          >
            <el-option
              v-for="item in attributes['商品类型'].items"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="addMessageModule">
          <a>商品价格：</a>
          <el-input
            v-model="addOfferPrice"
            placeholder="请输入商品价格"
            style="width: 200px"
            @input="checkInput"
            clearable
          />
        </div>
        <div class="addMessageModule">
          <a>商品折扣：</a>
          <el-select
            v-model="addOfferDiscount"
            placeholder="请选择商品折扣"
            style="width: 200px"
            clearable
          >
            <el-option
              v-for="item in attributes['商品折扣'].items"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="addMessageModule">
          <a>商品程度：</a>
          <el-select
            v-model="addOfferDegree"
            placeholder="请选择商品程度"
            style="width: 200px"
            clearable
          >
            <el-option
              v-for="item in attributes['商品程度'].items"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="addMessageModule">
          <a>出售地区：</a>
          <el-select
            v-model="addOfferLocal"
            placeholder="请选择商品地区"
            style="width: 200px"
            clearable
          >
            <el-option
              v-for="item in attributes['出售地区'].items"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="addMessageModule">
          <a>最终价格：</a>
          <el-input
            v-model="addFinalPrice"
            placeholder="商品最终的价格"
            style="width: 200px"
            disabled
          />
        </div>
      </div>
      <!-- 上传商品图片 -->
      <div class="offerImageModule">
        <div class="uploadImageModule">
          <span>商品图片：</span>
          <el-upload
            ref="upload"
            action="http://118.178.132.147:8088/person/uploadImage"
            :headers="{
              Authorization:
                'Bearer ' +
                (typeof localStorage !== 'undefined' &&
                localStorage.getItem('user')
                  ? JSON.parse(localStorage.getItem('user')).data.token
                  : ''),
            }"
            :limit="1"
            :show-file-list="true"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="photoSuccess"
            :on-remove="photoRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>
        <div class="uploadButtonModule">
          <el-button type="success" plain @click="uploadMessage"
            >上传商品信息</el-button
          >
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import PersonHead from "@/components/PersonHead.vue";
import PersonMenu from "@/components/PersonMenu.vue";
import PersonButtom from "@/components/PersonButtom.vue";
import { Search, Plus, Edit, Delete } from "@element-plus/icons-vue";
import { attributes } from "../assets/attributes.js";
import { ElMessage } from "element-plus";
import { ref, onMounted, watch } from "vue";
import request from "@/request/axios";

export default {
  components: { PersonHead, PersonMenu, PersonButtom },
  setup() {
    let offerID = ref(null);
    let tableData = ref();
    let pageNum = ref(1);
    let totalNum = ref(0);

    let addOfferModule = ref(false);
    let addOfferName = ref(null);
    let addOfferStyle = ref(null);
    let addOfferLocal = ref(null);
    let addOfferPrice = ref(null);
    let addOfferDiscount = ref(null);
    let addOfferDegree = ref(null);
    let addFinalPrice = ref(null);
    let addOfferImage = ref(null);

    const offerTable = () => {
      request
        .post("/person/offerList", {
          pageNum: pageNum.value,
          pageSize: 5,
          offerUser: JSON.parse(localStorage.getItem("user")).data.userID,
          offerID: offerID.value,
        })
        .then((res) => {
          if (res.code === "200") {
            tableData.value = res.data.data;
            totalNum.value = res.data.total;
          } else {
            tableData.value = [];
            ElMessage.warning(res.msg);
          }
        });
    };

    onMounted(offerTable);

    watch([addOfferPrice, addOfferDiscount], () => {
      if (addOfferPrice.value) {
        let discount = 1;
        switch (addOfferDiscount.value) {
          case "九五折":
            discount = 0.95;
            break;
          case "七八折":
            discount = 0.78;
            break;
          case "五折":
            discount = 0.5;
            break;
          default:
            break;
        }
        addFinalPrice.value = (addOfferPrice.value * discount).toFixed(2); // 计算最终价格并保留两位小数
      }
    });

    const currentChange = (current) => {
      pageNum.value = current;
      offerTable();
    };

    const photoSuccess = (imageUrl) => {
      console.log(imageUrl);
      addOfferImage.value = imageUrl.data;
      console.log(addOfferImage.value);
    };

    const photoRemove = (file) => {
      request
        .post("/person/photoRemove", { fileName: file.name })
        .then((res) => {
          console.log(res.msg);
        });
    };

    const uploadMessage = () => {
      if (
        addOfferImage.value != null &&
        addOfferName.value != null &&
        addOfferStyle.value != null &&
        addOfferPrice.value != null &&
        addOfferLocal.value != null &&
        addOfferDiscount.value != null &&
        addOfferDegree.value != null &&
        addFinalPrice.value != null
      ) {
        request
          .post("/person/offerAdd", {
            offerImage: addOfferImage.value,
            offerName: addOfferName.value,
            offerStyle: addOfferStyle.value,
            offerPrice: addOfferPrice.value,
            offerLocal: addOfferLocal.value,
            offerDiscount: addOfferDiscount.value,
            offerDegree: addOfferDegree.value,
            finalPrice: addFinalPrice.value,
            offerUser: JSON.parse(localStorage.getItem("user")).data.userID,
          })
          .then((res) => {
            console.log(res);
            if (res.code === "200") {
              ElMessage({
                showClose: true,
                message: "商品信息上传成功",
                type: "success",
              });
              offerTable(), (addOfferModule.value = false);
              (addOfferImage.value = null),
                (addOfferName.value = null),
                (addOfferStyle.value = null),
                (addOfferPrice.value = null),
                (addOfferLocal.value = null),
                (addOfferDiscount.value = null),
                (addOfferDegree.value = null),
                (addFinalPrice.value = null);
            } else {
              ElMessage.error(res.msg);
            }
          });
      } else {
        ElMessage.warning("所有信息都必须填写");
      }
    };

    const searchOffer = () => {
      console.log(offerID);
      offerTable();
      offerID.value = null;
    };

    const checkInput = () => {
      addOfferPrice.value = addOfferPrice.value
        .replace(/[^0-9.]/g, "")
        .replace(/\.(.*\.)+/, ".");
    };

    const alterOffer = (row) => {
      console.log(row);
    };

    const deleteOffer = (row) => {
      console.log(row.offerID);
      request
        .post("/person/offerDelete", { offerID: row.offerID })
        .then((res) => {
          if (res.code === "200") {
            ElMessage.success("商品信息删除成功");
            offerTable();
          } else {
            ElMessage.error(res.msg);
          }
        });
    };

    return {
      Plus,
      Edit,
      Delete,
      Search,
      tableData,
      offerID,
      pageNum,
      totalNum,
      attributes,
      offerTable,
      currentChange,
      searchOffer,
      checkInput,
      photoSuccess,
      photoRemove,
      alterOffer,
      deleteOffer,
      uploadMessage,
      addOfferModule,
      addOfferName,
      addOfferStyle,
      addOfferLocal,
      addOfferPrice,
      addOfferDiscount,
      addOfferDegree,
      addFinalPrice,
    };
  },
};
</script>

<style>
body {
  display: flex;
  flex-direction: column;
  width: 100vw;
  height: 100vh;
  margin: 0;
}

.personDataModule {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 68vh;
}

.datasModule {
  display: flex;
  flex-direction: row;
  width: 80%;
  height: 100%;
  background-color: #fff;
  border-inline: 2px solid #cacaca;
}

.personHandleModule {
  display: flex;
  align-items: center;
  width: 100%;
  height: 15%;
}

.personHandleModule span:nth-child(1) {
  margin-left: 6%;
  margin-right: 2%;
  font-family: "宋体";
  font-weight: 600;
}

.personTableModule {
  width: 100%;
  height: 75%;
}

.pagiNation {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 7vh;
  width: 100%;
}

.addOfferModule {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 500px;
}

.addOfferMessage {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 50%;
  height: 100%;
}

.addMessageModule {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  margin-block: 2%;
}

.addMessageModule a {
  font-size: 120%;
  font-family: "宋体";
  font-weight: 600;
}

.addMessageModule input {
  width: 40px;
}

.offerImageModule {
  display: flex;
  flex-direction: column;
  width: 50%;
  height: 100%;
}

.uploadImageModule {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  height: 90%;
}

.uploadImageModule span {
  margin-left: 5%;
  font-size: 120%;
  font-family: "宋体";
  font-weight: 600;
}

.uploadButtonModule {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 10%;
}
</style>